/**
* 描述：安全中心
*/
<style lang="scss" scoped>
  @import '../index';
</style>
<template>
  <div style="width:100%; height:100%;">
    <div class="com-main-title">
      <span class="tit">安全中心</span>
      <div class="clear"></div>
    </div>
    <div class="securityCenter-list">
      <!--<div class="one">-->
        <!--<b class="iconUCenter iconUCenter_userName"></b>-->
        <!--<span class="name">用户名</span>-->
        <!--<span class="value">{{userInfo.screenName}}</span>-->
        <!--&lt;!&ndash;<a class="modifyBtn" @click="modifyNameFormShow = true;">修改</a>&ndash;&gt;-->
        <!--<div class="clear"></div>-->
        <!--<div class="hr"></div>-->
      <!--</div>-->
      <div class="one">
        <b class="iconUCenter iconUCenter_bindPhone"></b>
        <span class="name">绑定手机</span>
        <span class="value">{{userInfo.phone}}</span>
        <a class="modifyBtn" @click="modifyPhoneFormShow = true;">修改</a>
        <div class="clear"></div>
        <div class="hr"></div>
      </div>
      <div class="one">
        <b class="iconUCenter iconUCenter_signPassword"></b>
        <span class="name">登录密码</span>
        <span class="value">**********</span>
        <a class="modifyBtn" @click="modifyPasswordFormShow = true;">修改</a>
        <div class="clear"></div>
        <div class="hr"></div>
      </div>
    </div>

    <!--修改用户名-->
    <Modal v-model="modifyNameFormShow" :mask-closable="false" :closable="false" width="420" class="noTopBottomBorder">
      <p slot="header" style="color:#000;text-align:center;font-weight: bold;font-size: 18px;">
        <span>修改用户名</span>
      </p>
      <div style="transform: translateX(0%) translateZ(0px);margin-right:20px;">
        <el-form ref="userNameForm" :model="userNameForm" :rules="userNameFormRules" label-width="100px">
          <el-form-item label="新用户名：" prop="screenName">
            <el-input v-model="userNameForm.screenName" type="text" placeholder="仅允许数字、字母、下划线、中划线"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" style="width:220px;margin:-20px auto 20px;">
        <i-button type="primary" size="large" @click="modifyUserName('userNameForm')" style="width:100px;">确认修改</i-button>
        <i-button size="large" @click="modifyNameFormShow = false" style="width:100px;">取消</i-button>
      </div>
    </Modal>
    <!--修改手机号-->
    <Modal v-model="modifyPhoneFormShow" :mask-closable="false" :closable="false" width="520" class="noTopBottomBorder">
      <p slot="header" style="color:#000;text-align:center;font-weight: bold;font-size: 18px;">
        <span>更换绑定手机</span>
      </p>
      <div style="transform: translateX(0%) translateZ(0px);margin-right:20px;">
        <el-form ref="changeForm" :model="changeForm" :rules="cpValidate" label-width="100px">
          <el-form-item label="新手机号">
            <input type="text" autocomplete="off" class="form-control" style="width:340px;border: 1px #ccc solid;padding:0 10px;" v-model="changeForm.phone" placeholder="手机号" />
          </el-form-item>
          <el-form-item label="" style="width:440px;">
            <p style="width:30%;font-size: 12px;line-height: 30px;float: left;width:150px;height:40px;">
              <img :src="`/api/pub/captcha.jpg?randKey=${code}`" alt="">
            </p>
            <a @click="rndNum()" style="margin-top:15px;margin-left:10px;float: left;font-size: 12px;"> 刷新</a>
            <input type="text" placeholder="请输入图片验证码" v-model="captcha" style="width:140px;border: 1px #ccc solid;font-size: 12px;line-height: 30px;padding:4px 10px;float: right;color:#666;"/>
          </el-form-item>
          <el-form-item label="验证码" style="width:440px;margin-top:-20px;">
            <input type="text" placeholder="验证码" v-model="changeForm.smsCode" style="width:200px;border: 1px #ccc solid;padding:0 10px;float: left;"/>
            <a @click="getSms()" style="width:140px;border: 1px #0078ff solid;padding:0 10px;float: right;background:#0078ff;color: #fff;font-size: 12px;text-align: center">{{fonts}}</a>
          </el-form-item>
          <div class="clear"></div>
        </el-form>
      </div>
      <div slot="footer" style="width:220px;margin:-20px auto 20px;">
        <i-button type="primary" size="large" @click="changePhoneFuc('changeForm')" style="width:100px;">确认修改</i-button>
        <i-button size="large" @click="modifyPhoneFormShow = false" style="width:100px;">取消</i-button>
      </div>
    </Modal>
    <!--修改登录密码-->
    <Modal v-model="modifyPasswordFormShow" :mask-closable="false" :closable="false" width="420" class="noTopBottomBorder">
      <p slot="header" style="color:#000;text-align:center;font-weight: bold;font-size: 18px;">
        <span>修改登录密码</span>
      </p>
      <div style="transform: translateX(0%) translateZ(0px);margin-right:20px;">
        <el-form ref="form" :model="form" :rules="validate" label-width="100px">
          <el-form-item label="原密码">
            <el-input v-model="form.oldPassword" type="password"></el-input>
          </el-form-item>
          <el-form-item label="新密码">
            <el-input v-model="form.newPassword" type="password"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" style="width:220px;margin:-20px auto 20px;">
        <i-button type="primary" size="large" @click="modifyPassword('form')" style="width:100px;">确认修改</i-button>
        <i-button size="large" @click="modifyPasswordFormShow = false" style="width:100px;">取消</i-button>
      </div>
    </Modal>


  </div>
</template>
<script>
  import { mapState, mapActions } from 'vuex';
  import { changePassword, changePhone, modifyUser } from '@/service/web/user/userService';
  import { sendSmsCode } from '@/service/web/login/loginService';
  import md5 from 'js-md5';
  export default {
    computed: {
      ...mapState([
        'userInfo'
      ])
    },
    data () {
      return {
        modifyNameFormShow: false,
        modifyPasswordFormShow: false,
        modifyPhoneFormShow: false,
        userNameForm: {},
        userNameFormRules: {
          screenName: [
            {required: true, message: '用户名不能为空', trigger: 'blur change'},
            {pattern: '^^[\\w_-]{5,20}$', message: '仅允许数字、字母、下划线、中划线', trigger: 'blur change'}
          ]
        },
        form: {
          oldPassword: '',
          newPassword: ''
        },
        validate: {
          oldPassword: [
            {required: true, message: '原始密码不能为空', trigger: 'blur change'}
          ],
          newPassword: [
            {required: true, message: '新密码不能为空', trigger: 'blur change'},
            {pattern: '^(?![0-9]+$)(?![a-zA-Z]+$)[,.#%’+*-:;^_`0-9A-Za-z]{6,20}$', message: '密码6-20位，必须同时含有数字、字母', trigger: 'blur change'}
          ]
        },
        changeForm: {},
        cpValidate: {
          phone: [
            {required: true, message: '手机号不能为空', trigger: 'blur change'},
            {pattern: '^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$', message: '手机号格式不正确', trigger: 'blur change'}
          ],
          smsCode: [
            {required: true, message: '验证码不能为空', trigger: 'blur change'}
          ]
        },
        picture: null,
        code: '',
        captcha: '',
        isSend: false, // 是否已发送短信验证码
        fonts: '获取短信验证码',
        timeInterval: null, // 获取短信时间倒计时
        second: 60
      };
    },
    async mounted () {
      this.init();
      if (this.userInfo.username) {
        await this.getUserInfo();
      }
      console.log(this.userInfo);
    },
    methods: {
      ...mapActions([
        'getUserInfo'
      ]),
      init () {
        this.rndNum();
      },
      //
      // 生成随机数 5位 即 随机生成图片
      rndNum () {
        let xxx = Math.random().toString(36).substr(2);
        let aa = xxx.slice(0, 5);
        this.code = aa;
      },
      // 发送短信验证码
      async getSms () {
        if (this.isSend) return;
        try {
          if (!this.changeForm.phone) {
            this.$message({
              message: '请输入手机号',
              type: 'warning'
            });
            return;
          }
          if (!this.captcha) {
            this.$message({
              message: '请输入图片验证码',
              type: 'warning'
            });
            return;
          }
          await sendSmsCode({phone: this.changeForm.phone}, {phone: this.changeForm.phone, randKey: this.code, captcha: this.captcha}); // 获取短信验证码接口
          this.isSend = true;
          this.second = 60;
          this.$message({message: '发送成功，请注意查收短信！', type: 'success'});
          this.timeInterval = setInterval(() => {
            if (this.second === 0) {
              this.fonts = '点击按钮重新发送';
              clearInterval(this.timeInterval);
              this.rndNum();
              this.code = '';
              this.isSend = false;
            } else {
              this.fonts = '剩余' + this.second + '秒';
              this.second = this.second - 1;
            }
          }, 1000);
        } catch (e) {
          this.$message({
            message: e,
            type: 'error'
          });
        }
      },
      // 修改密码
      modifyPassword (name) {
        this.$refs[name].validate((valid) => {
          if (!valid) return;
          this.$confirm('确定修改密码吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            let para = {
              oldPassword: md5(this.form.oldPassword),
              newPassword: this.form.newPassword
            };
            await changePassword(para);
            this.$Notice.success({title: '修改成功'});
            this.$router.push('/login');
          }).catch(() => {
          });
        });
      },
      // 手改手机号
      changePhoneFuc (name) {
        this.$refs[name].validate((valid) => {
          if (!valid) return;
          this.$confirm('确定修改手机吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            let para = {
              phone: this.changeForm.phone,
              smsCode: this.changeForm.smsCode
            };
            await changePhone(para);
            this.$Notice.success({title: '修改成功'});
            this.$router.push('/login');
          }).catch(() => {
          });
        });
      },
      // 修改用户名
      modifyUserName (name) {
        this.$refs[name].validate((valid) => {
          if (!valid) return;
          this.$confirm('确定修改用户名吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            let payload = Object.assign({}, this.userInfo);
            payload.screenName = this.userNameForm.screenName;
            payload.birth = this._hyTool.DateFormat(new Date(payload.birth), 'yyyy-MM-dd hh:mm:ss');
            await modifyUser(payload);
            this.$Notice.success({title: '修改成功'});
            this.$router.push('/login');
          }).catch(() => {
          });
        });
      }
    },
    watch: {
    },
    destoryed: function () {
      clearInterval(this.timeInterval);
    }
  };
</script>
